from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from . import serializers
from rest_framework.response import Response
from django_redis import get_redis_connection
from rest_framework import status
import pickle, base64
from goods.models import SKU




# url(r'^carts/$', views.CartView.as_view()),
class CartView(APIView):
    """
    购物车增删改查
    用户登录可以访问
    用户未登录也可以访问
    """

    # permission_classes = [IsAuthenticated] # 如果加了权限，未登录用户无法访问，没加权限登录用户无意义
    def perform_authentication(self, request):
        """执行认证的方法，
        重写之后，直接pass,不对用户做认证，认证的行为放具体的业务逻辑需要的地方，程序员自己写代码认证，
        如果写pass就是取消该视图的认证行为，需要自己写认证代码
        """
        pass



    def post(self, request):
        """添加购物车"""

        # 使用序列化器对购物车数据进行校验
        serializer = serializers.CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 读取校验之后的数据
        sku_id = serializer.data.get('sku_id')
        count = serializer.data.get('count')
        selected = serializer.data.get('selected')

        # 判断用户是否登录
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            # 用户已登录，操作redis数据库
            # 获取连接到redis对象
            redis_coon = get_redis_connection('cart')
            # 创建管道(优化代码)
            pl = redis_coon.pipeline()

            # 给redis购物车做增量存储，计算
            # redis_conn.hincrby(name, key, amount=1)
            pl.hincrby('cart_%s' % user.id, sku_id, count)

            # 存储是否被勾选
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)

            # 执行管道
            pl.execute()

            # 响应
            return Response(serializer.data,status=status.HTTP_201_CREATED)
        else:
            # 用户未登录，操作cookie
            # 获取用户浏览器中的cookie购物车数据
            cart_str = request.COOKIES.get('cart')
            if cart_str:
                # 将购物车字符窜转换成bytes类型的购物车字符窜
                cart_str_bytes = cart_str.encode()
                # 将bytes类型的购物车字符窜转成bytes类型的字典
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 将bytes的字典转成标准字典
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                cart_dict = {}   # 保证用户即使是第一次使用cookie保存购物车数据，也有字典对象可以操作

            # 添加购物车数据到字典
            if sku_id in cart_dict:
                # 表示要添加的商品，在购物车已经存在
                origin_count = cart_dict[sku_id]['count']
                count += origin_count

            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            # 需要将cart_dict数据转成字符窜cookie_cart_str
            cookie_cart_dict_bytes = pickle.dumps(cart_dict)
            cooke_cart_str_bytes = base64.b64encode(cookie_cart_dict_bytes)
            cookie_cart_str = cooke_cart_str_bytes.decode()

            # 需要将cookie_cart_str数据写入浏览器的cookie
            response = Response(serializer.data, status=status.HTTP_201_CREATED)
            response.set_cookie('cart', cookie_cart_str)

            return response


    def get(self, request):
        """查询购物车"""
        # 判断用户是否登录
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            # 用户已登录，操作redis购物车

            # 创建连接到redis的对象
            redis_coon = get_redis_connection('cart')

            # 查询redis中的购物车数据
            # 注意点：python3中的从redis读取的数据都是bytes类型的数据
            # redis_cart_dict = {b'sku_id_1': b'count_1', b'sku_id_2': b'count_2'}
            redis_cart_dict = redis_coon.hgetall('cart_%s' % user.id)

            # 查询是否被勾选
            # redis_selected = [b'sku_id_1']
            redis_selected = redis_coon.smembers('selected_%s' % user.id)

            """
               {
                   sku_id10: {
                       "count": 10,  // 数量
                       "selected": True  // 是否勾选
                   },
                   sku_id20: {
                       "count": 20,
                       "selected": False
                   },
                   ...
               }
           """
            # 定义空的字典
            cart_dict = {}
            for sku_id, count in redis_cart_dict.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in redis_selected     # 如果sku_id在redis_selected中，返回True ;反之,返回False
                }
        else:
            # 用户未登录，操作cookie购物车
            # 获取用户浏览器中的cookie购物车数据
            cart_str = request.COOKIES.get('cart')
            if cart_str:
                # 将购物车字符窜转成bytes类型的购物车字符窜
                cart_str_bytes = cart_str.encode()
                # 将bytes类型的购物车字符窜转成bytes类型的字典
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 将bytes类型的字典转成标准字典
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                cart_dict = {}

        # 使用序列化器对redis购物车或者cookie购物车进行统一的序列化
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)

        # 需要给每一个sku增加count和selected属性
        for sku in skus:
            sku.count = cart_dict[sku.id]['count']
            sku.selected = cart_dict[sku.id]['selected']

        # 创建序列化器对象，完成序列化，并响应
        serializer = serializers.CartSKUSerializer(skus, many=True)
        return Response(serializer.data)


    def put(self, request):
        """修改购物车"""
        # 使用序列化器对购物车数据进行校验
        serializer = serializers.CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 读取校验之后的数据
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')

        # 判断用户是否登录
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            # 用户已登录，操作redis购物车
            # 获取连接到redis对象
            redis_coon = get_redis_connection('cart')
            # 创建管道
            pl = redis_coon.pipeline()

            # 操作redis修改购物车数据，将已存在的商品数量覆盖即可
            pl.hset('cart_%s' % user.id, sku_id, count)

            # 是否勾选
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            else:
                pl.srem('selected_%s' % user.id, sku_id)

            # 执行管道
            pl.execute()

            # 响应

            return Response(serializer.data)

        else:
            # 用户未登录，操作cookie购物车
            # 获取用户浏览器中的cookie购物车数据
            cart_str = request.COOKIES.get('cart')
            if cart_str:
                # 将购物车字符窜转成bytes类型的购物车字符窜
                cart_str_bytes = cart_str.encode()
                # 将bytes类型的购物车字符窜转成bytes类型的字典
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 将bytes类型的字典转为标准字典
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                cart_dict = {}   # 保证用户即使是第一次操作cookie保存购物车数据，也有字典对象可以操作

            # 添加购物车数据到字典
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            # 需要将cart_dict 转成字符窜cookie_cart_str
            cookie_cart_dict_bytes = pickle.dumps(cart_dict)
            cookie_cart_str_bytes = base64.b64encode(cookie_cart_dict_bytes)
            cookie_cart_str = cookie_cart_str_bytes.decode()

            # 需要将cookie_cart_str写入到浏览器的cookie
            response = Response(serializer.data,)
            response.set_cookie('cart', cookie_cart_str)

            # 响应
            return response


    def delete(self, request):
        """删除购物车"""

        # 创建序列化器对象，并验证字段
        serializer = serializers.CartDeleteSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 获取校验后的参数
        sku_id = serializer.validated_data.get('sku_id')

        # 获取user，判断用户是否登录
        try:
            user = request.user
        except Exception:
            user = None

        # 判断用户是否登录
        if user is not None and user.is_authenticated:
            # 用户已登录，操作redis购物车
            # 创建连接到redis对象
            redis_conn = get_redis_connection('cart')
            # 创建管道
            pl = redis_conn.pipeline()
            # 删除数据
            pl.hdel('cart_%s' % user.id, sku_id)
            pl.srem('selected_%s' % user.id, sku_id)
            # 执行管道
            pl.execute()

            # 响应:删除数据后，没有响应的对象，只需响应状态码即可
            return Response(status=status.HTTP_204_NO_CONTENT)

        else:
            # 用户未登录，操作cookie购物车
            # 获取用户浏览器中cookie购物车数据
            cart_str = request.COOKIES.get('cart')
            if cart_str:
                # 将购物车字符窜转成bytes类型的字符窜
                cart_str_bytes = cart_str.encode()
                # 将bytes类型的字符窜转成bytes类型的字典
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                #　将bytes类型的字典转成标准字典
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                cart_dict = {}  # 保证用户即使是第一次操作cookie保存购物车数据，也有字典对象可以操作


            # 创建响应对象
            response = Response(status=status.HTTP_204_NO_CONTENT)


            if sku_id in cart_dict:
                del cart_dict[sku_id]

                # 需要将cart_dict转成字符窜cookie_cart_str
                cookie_cart_dict_bytes = pickle.dumps(cart_dict)
                cookie_cart_str_bytes = base64.b64encode(cookie_cart_dict_bytes)
                cookie_cart_str = cookie_cart_str_bytes.decode()

                # 需要将cookie_cart_str写入到cookie
                response.set_cookie('cart', cookie_cart_str)

            # 响应结果
            return response


        pass



class CartSelectAllView(APIView):
    """购物车全选"""

    def perform_authentication(self, request):
        """执行认证的方法，
        重写之后，直接pass，不对用户做认证，认证的行为放在具体的业务逻辑需要的地方，程序员自己写代码认证，
        如果写pass就是取消该试图的认证行为，需要自己写认证代码"""

        pass

    def put(self, request):
        # 使用序列化器对购物车数据进行校验
        serializer = serializers.CartSelectAllSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 读取序列化校验之后的数据
        selected = serializer.validated_data.get('selected')

        # 判断用户是否登录
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            # 用户登录，操作redis购物车
            # 创建连接redis对象
            redis_coon = get_redis_connection('cart')
            cart = redis_coon.hgetall('cart_%s' % user.id)
            sku_id_list = cart.keys()

            if selected:
                # 全选
                redis_coon.sadd('selected_%s' % user.id, *sku_id_list)
            else:
                # 取消全选
                redis_coon.srem('selected_%s' % user.id, *sku_id_list)

            # 响应结果
            return Response({'message': 'OK'})
        else:
            # 用户未登录，操作cookie购物车
            #　获取用户浏览器中的cookie购物车数据
            cart = request.COOKIES.get('cart')

            # 创建响应对象
            response = Response({'message': 'OK'})
            if cart is not None:
                # 将购物车字符窜转成bytes类型的字符窜
                cart_bytes = cart.encode()
                # 将bytes类型的字符窜转成bytes类型的字典
                cart_dict_bytes = base64.b64decode(cart_bytes)
                # 将bytes类型的字典数据转成标准字典
                cart_dict = pickle.loads(cart_dict_bytes)

                for sku_id in cart_dict:
                    cart_dict[sku_id]['selected'] = selected
                # 需要将cart_dict转成字符窜cookie_cart
                cart_dict_bytes = pickle.dumps(cart_dict)
                cart_str_bytes = base64.b64encode(cart_dict_bytes)
                cart_str = cart_str_bytes.decode()

                # 需要将cart_str数据写入浏览器的cookie
                response.set_cookie('cart', cart_str)

            # 响应结果
            return response




